from bytestohuman import bytes2human
import psutil,time
def getNetstats():
    network_date_sent_recive = [bytes2human(psutil.net_io_counters().bytes_sent),
                                bytes2human(psutil.net_io_counters().bytes_recv),
                                psutil.net_io_counters().packets_sent,
                                psutil.net_io_counters().packets_recv
                                ]
    return network_date_sent_recive
def getNicinfo():
    nics_info = []
    for k,v in psutil.net_io_counters(pernic=True).items():
        nic_info = []
        if v[0]==0 and v[1]==0:#如果网卡的发送数据和接收数据同时为零，则网卡不会统计在内
            continue
        else:
            try:
                if psutil.net_if_addrs()[k][1][2] is not None:  # 主要目的是过滤掉IPV6地址
                    nic_info.append(k)  # 网卡名称
                    nic_info.append(psutil.net_if_addrs()[k][1][1])  # 网卡IP地址
                    nic_info.append(psutil.net_if_addrs()[k][1][2])  # 网卡子网掩码
                    nic_info.append(v[0])  # 网卡发送字节数量
                    nic_info.append(v[1])  # 网卡接收字节数量
                    nic_info.append(v[2])  # 网卡发送数据包数量
                    nic_info.append(v[3])  # 网卡接受数据包数量
                    nics_info.append(nic_info)
            except:
                #如果调取网卡数据错误，则跳过本次循环
                continue





    return sorted(nics_info, key=lambda nic: nic[0], reverse=True) #以网卡发送数量进行降序排序



if __name__ == "__main__":
        print(getNicinfo())
        try:
            print(" %-30s %-15s %-15s %-10s %-10s %-15s %-15s" %("NAME",
                                                                 "IP Address",
                                                                 "Net Mask",
                                                                 "Sent","Recive",
                                                                 "Sent/packages",
                                                                 "Recive/packages",
                                        ))
            for i in getNicinfo():
                print(" %-30s %-15s %-15s %-10s %-10s %-15s %-10s"%(i[0],
                                                       i[1],
                                                       i[2],
                                                       bytes2human(i[3]),
                                                       bytes2human(i[4]),
                                                       i[5],
                                                       i[6]
                                                       ))
            time.sleep(1)
        except:
            pass

